package org.goyo.main.services.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.goyo.main.domain.entity.system.SysRoleResource;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.services.system.ISystemService;
import org.goyo.main.web.controller.system.SessionUtil;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
@Transactional
public class SecurityMetadataSource implements FilterInvocationSecurityMetadataSource{
	private ISystemService systemService;
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}
	/**
	 * 返回所请求资源所需要的权限
	 */
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
	  // object 是一个URL，被用户请求的url。
	  String url = ((FilterInvocation) object).getRequestUrl();
	  int firstQuestionMarkIndex = url.indexOf("?");
	  if (firstQuestionMarkIndex != -1) {
	       url = url.substring(0, firstQuestionMarkIndex);
	  }
	 //通过url查找资源对应资源
	  Map<String, List<SysRoleResource>> authoritys = systemService.getAllAuthority();
	  List<SysRoleResource> roleResources = authoritys.get(url);
	  if(roleResources != null && roleResources.size() > 0){
		  for(SysRoleResource roleResource : roleResources){
			  configAttributes.add(new SecurityConfig(roleResource.getRoleId()));
		  }
	  }
	  if(configAttributes.size() == 0){
		  Object obj = SessionUtil.getAttribute("user");
		  if(obj != null){
			  if(((SysUser)obj).isSupper()){
				  configAttributes.add(new SecurityConfig("GOYO"));
			  }else{
				  configAttributes.add(new SecurityConfig(((SysUser)obj).getUuid()));
			  }
		  }else{
			  configAttributes.add(new SecurityConfig("GOYO"));
		  }
	  }
	return configAttributes;
	}

	public boolean supports(Class<?> arg0) {
		return true;
	}

	public ISystemService getSystemService() {
		return systemService;
	}
	public void setSystemService(ISystemService systemService) {
		this.systemService = systemService;
	}
	
}
